import 'dart:async';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'adapter.dart';
import 'hm_navigator.dart';
import 'modules/common_module.dart';

/// 路由表

class HMRoutes {
  HMRoutes._();

  /// 路由表
  static final List<RouteBase> _routes = [];

  /// 适配器
  static List<RoutesAdaptor> _adapters = [];

  /// --------------------------------------------------
  /// 模块

  /// 公共模块
  static final common = CommonModule();

  /// --------------------------------------------------
  /// 加载路由
  static void loadRoutes(List<RoutesAdaptor> adapters) {
    _adapters = adapters;
  }

  /// 缓存路由配置
  static RouterConfig<Object>? _cacheRouterConfig;

  /// 清除路由缓存
  static void clearRouterCache() {
    _cacheRouterConfig = null;
  }

  /// 路由配置
  static RouterConfig<Object>? routerConfig({
    String? initialLocation,
    bool debugLogDiagnostics = false,
    List<NavigatorObserver>? observers,
    GlobalKey<NavigatorState>? navigatorKey,
    FutureOr<String?> Function(BuildContext, GoRouterState)? redirect,
    List<String>? tabbarRouterPaths,
    StatefulShellRoutePageBuilder? pageBuilder,
  }) {
    if (_cacheRouterConfig != null) return _cacheRouterConfig;
    navigatorKey ??= GlobalKey<NavigatorState>();
    HMNavigator.setNavigatorKey(navigatorKey);
    observers ??= [];
    observers.add(HMNavigator.routeObserver);
    _cacheRouterConfig = GoRouter(
      initialLocation: initialLocation,
      debugLogDiagnostics: debugLogDiagnostics,
      observers: observers,
      navigatorKey: navigatorKey,
      redirect: redirect,
      routes: _resetRoutes(
        tabbarRouterPaths: tabbarRouterPaths,
        navigatorKey: navigatorKey,
        pageBuilder: pageBuilder,
      ),
    );
    return _cacheRouterConfig;
  }

  /// 重置路由表
  static List<RouteBase> _resetRoutes({
    List<String>? tabbarRouterPaths,
    GlobalKey<NavigatorState>? navigatorKey,
    StatefulShellRoutePageBuilder? pageBuilder,
  }) {
    /// 清空路由表
    _routes.clear();

    /// 添加路由表
    for (final adapter in _adapters) {
      adapter.registerRoutes(HMNavigator.shared);
      _routes.addAll(adapter.allRoutes(navigatorKey: navigatorKey));
    }

    /// 处理tabbar
    if (tabbarRouterPaths == null) return _routes;
    List<StatefulShellBranch> tabbarRouters = [];
    for (final path in tabbarRouterPaths) {
      final result = _routes
          .where((element) {
            if (element is GoRoute) {
              return element.path == path;
            }
            return false;
          })
          .map(
            (e) => StatefulShellBranch(
              routes: [e],
            ),
          )
          .toList();
      tabbarRouters.addAll(result);
    }

    _routes.removeWhere((element) {
      if (element is GoRoute) {
        return tabbarRouterPaths.contains(element.path);
      }
      return false;
    });
    final tabbarRouter = StatefulShellRoute.indexedStack(
      parentNavigatorKey: navigatorKey,
      branches: tabbarRouters,
      pageBuilder: pageBuilder,
    );
    _routes.insert(0, tabbarRouter);
    return _routes;
  }
}
